<?php
namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Statistics;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;

class StatisticsController extends Controller {
    public function __construct()
    {
        $this->Statistics = new Statistics();
    }
    //公司数据（总览）
    public function getOverView($id){
        $cmpId = $id;
        //访客
        $visitors = DB::table('visitorHistory')->where([['cmpId', '=', $cmpId],['isInvite','=','0']])->count();
        //邀请
        $invite = DB::table('visitorHistory')->where([
            ['cmpId', '=', $cmpId],
            ['IsInvite', '=', 1],
        ])->count();
        //使用天数
        $date = DB::table('userAdm')
            ->join('cmpInfo', 'cmpInfo.userId', '=', 'userAdm.id')
            ->select('userAdm.createdAt', 'userAdm.updatedAt')
            ->where('cmpInfo.id', '=', $cmpId)
            ->first();
        if(empty($date)){
            $time = 0;
        }else{
            $startTime = $date->createdAt;
            $endTime = $date->updatedAt;
            $time = $endTime - $startTime;
        }
        $days = ceil($time/24/60/60);
        //通知
        $word = 'company_id_'.$cmpId.'_count';
        try{
            $notice =(integer)Redis::get($word);
        }catch(\exception $e){
            $notice = 0;
        }
        $data = ['visitors'=>$visitors,'invite'=>$invite,'report'=>$notice,'days'=>$days];
        return response()->json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
    }
    //历史数据
    public function getHistory(Request $request){
        $data = $request->all();
        $type = $data['type'];
        $cmpId = $data['cmpId'];
        if($type){
            switch($type) {
                //一周
                case 2:
                    $endtime = time();
                    $starttime = $endtime - 24 * 3600 * 7;
                    $orders = DB::table('visitorHistory')
                        ->select(DB::raw("from_unixtime(visitTime,'%Y/%m/%d') as hours"), DB::raw("count(*) as count"))
                        ->whereBetween('visitTime', [$starttime, $endtime])
                        ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
                        ->groupBy(DB::raw("from_unixtime(visitTime,'%Y/%m/%d')"))
                        ->get()
                        ->toarray();
                    for ($i = 0; $i < 7; $i++) {
                        $h = 6-$i;
                        $list['day'][$i] = date('Y/m/d', strtotime("-$h day"));
                    }
                    $list['number'] = [0,0,0,0,0,0,0];
                    if (!empty($orders)) {
                        foreach ($orders as $k) {
                            if (in_array($k->hours, $list['day'])) {
                                $key = array_search($k->hours,$list['day']);
                                $list['number'][$key] = $k->count;
                            }
                        }
                    }
                    return response()->json(['code' => 200, 'msg' => '成功', 'data' => $list]);
                    break;
                //30天
                case 3:
                    $endtime = time();
                    $starttime = $endtime - 24 * 3600 * 30;
                    $orders = DB::table('visitorHistory')
                        ->select(DB::raw("from_unixtime(visitTime,'%Y/%m/%d') as hours"), DB::raw("count(*) as count"))
                        ->whereBetween('visitTime', [$starttime, $endtime])
                        ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
                        ->groupBy(DB::raw("from_unixtime(visitTime,'%Y/%m/%d')"))
                        ->get()
                        ->toarray();
                    for ($i = 0; $i < 30; $i++) {
                        $h = 29-$i;
                        $list['day'][$i] = date('Y/m/d', strtotime("-$h day"));
                        $list['number'][$i] = 0;
                    }
                    if (!empty($orders)) {
                        foreach ($orders as $k) {
                            if (in_array($k->hours, $list['day'])) {
                                $key = array_search($k->hours,$list['day']);
                                $list['number'][$key] = $k->count;
                            }
                        }
                    }
                    $s = -1;
                    for ($i = 0; $i < 10; $i++) {
                        $h = 30 - $i * 3;
                        $k = 27 - $i * 3;
                        $listInfo['day'][$i] = date("m/d", strtotime("-$h day")) . '-' . date("m/d", strtotime("-$k day"));
                        $listInfo['number'][$i] = $list['number'][++$s] + $list['number'][++$s] + $list['number'][++$s];
                    }
                    return response()->json(['code' => 200, 'msg' => '请求成功', 'data' => $listInfo]);
                    break;
                //90天
                case 4:
                    $endtime = time();
                    $starttime = $endtime - 24 * 3600 * 90;
                    $orders = DB::table('visitorHistory')
                        ->select(DB::raw("from_unixtime(visitTime,'%Y/%m/%d') as hours"), DB::raw("count(*) as count"))
                        ->whereBetween('VisitTime', [$starttime, $endtime])
                        ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
                        ->groupBy(DB::raw("from_unixtime(visitTime,'%Y/%m/%d')"))
                        ->get()
                        ->toarray();
                    for ($i = 0; $i < 90; $i++) {
                        $h = 89-$i;
                        $list['day'][$i] = date('Y/m/d', strtotime("-$h day"));
                        $list['number'][$i] = 0;
                    }
                    if (!empty($orders)) {
                        foreach ($orders as $k) {
                            if (in_array($k->hours, $list['day'])) {
                                $key = array_search($k->hours,$list['day']);
                                $list['number'][$key] = $k->count;
                            }
                        }
                    }
                    $s = -1;
                    for ($i = 0; $i < 10; $i++) {
                        $h = 90 - $i * 9;
                        $k = 81 - $i * 9;
                        $listInfo['day'][$i] = date("m/d", strtotime("-$h day")) . '-' . date("m/d", strtotime("-$k day"));
                        $listInfo['number'][$i] =
                            $list['number'][++$s] + $list['number'][++$s] +
                            $list['number'][++$s] + $list['number'][++$s] +
                            $list['number'][++$s] + $list['number'][++$s] +
                            $list['number'][++$s] + $list['number'][++$s] +
                            $list['number'][++$s];
                    }
                    return response()->json(['code' => 200, 'msg' => '请求成功', 'data' => $listInfo]);
                    break;
                //180天
                case 5:
                    $endtime = time();
                    $starttime = $endtime - 24 * 3600 * 180;
                    $orders = DB::table('visitorHistory')
                        ->select(DB::raw("from_unixtime(visitTime,'%Y/%m') as hours"), DB::raw("count(*) as count"))
                        ->whereBetween('visitTime', [$starttime, $endtime])
                        ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
                        ->groupBy(DB::raw("from_unixtime(visitTime,'%Y/%m')"))
                        ->get()
                        ->toarray();
                    for ($i = 0; $i < 6; $i++) {
                        $h = 5-$i;
                        $list['day'][$i] = date('Y/m', strtotime("-$h month"));
                        $list['number'][$i] = 0;
                    }
                    if (!empty($orders)) {
                        foreach ($orders as $k) {
                            if (in_array($k->hours, $list['day'])) {
                                $key = array_search($k->hours,$list['day']);
                                $list['number'][$key] = $k->count;
                            }
                        }
                    }
                    return response()->json(['code' => 200, 'msg' => '请求成功', 'data' => $list]);
                    break;
                //360天
                case 6:
                    $endtime = time();
                    $starttime = $endtime - 24 * 3600 * 360;
                    $orders = DB::table('visitorHistory')
                        ->select(DB::raw("from_unixtime(visitTime,'%Y/%m') as hours"), DB::raw("count(*) as count"))
                        ->whereBetween('visitTime', [$starttime, $endtime])
                        ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
                        ->groupBy(DB::raw("from_unixtime(visitTime,'%Y/%m')"))
                        ->get()
                        ->toarray();
                    for ($i = 0; $i < 12; $i++) {
                        $h = 11-$i;
                        $list['day'][$i] = date('Y/m', strtotime("- $h month"));
                        $list['number'][$i] = 0;
                    }
                    if (!empty($orders)) {
                        foreach ($orders as $k) {
                            if (in_array($k->hours, $list['day'])) {
                                $key = array_search($k->hours,$list['day']);
                                $list['number'][$key] = $k->count;
                            }
                        }
                    }
                    return response()->json(['code' => 200, 'msg' => '请求成功', 'data' => $list]);
                    break;
                default:
                    //当天
                    $starttime = strtotime(date('Ymd'));
                    $endtime = time();
                    $orders = DB::table('visitorHistory')
                        ->select(DB::raw("from_unixtime(visitTime,'%H') as hours"), DB::raw("count(*) as count"))
                        ->whereBetween('visitTime', [$starttime, $endtime])
                        ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
                        ->groupBy(DB::raw("from_unixtime(visitTime,'%H')"))
                        ->get()
                        ->toArray();
                    for ($i = 0; $i < 24; $i++) {
                        if ($i < 10) {
                            $key = '0' . $i;
                        } else {
                            $key = (string)$i;
                        }
                        $list['day'][$i] = $key;
                        $list['number'][$i] = 0;
                    }
                    if (!empty($orders)) {
                        foreach ($orders as $k) {
                            if (in_array($k->hours, $list['day'])) {
                                $key = array_search($k->hours,$list['day']);
                                $list['number'][$key] = $k->count;
                            }
                        }
                    }
                    $infoList['number'][0] = 0;
                    for ($h = 0; $h < count($list['day']); $h++) {
                        if ($h < 6) {
                            $infoList['number'][0] += $list['number'][$h];
                        }
                    }
                    $infoList['day'][0] = '00:00-06:00';
                    $infoList['day'][1] = '06:00-08:00';
                    $infoList['day'][2] = '08:00-10:00';
                    $infoList['day'][3] = '10:00-12:00';
                    $infoList['day'][4] = '12:00-14:00';
                    $infoList['day'][5] = '14:00-16:00';
                    $infoList['day'][6] = '16:00-18:00';
                    $infoList['day'][7] = '18:00-20:00';
                    $infoList['day'][8] = '20:00-22:00';
                    $infoList['day'][9] = '22:00-24:00';
                    $infoList['number'][1] = $list['number'][6] + $list['number'][7];
                    $infoList['number'][2] = $list['number'][8] + $list['number'][9];
                    $infoList['number'][3] = $list['number'][10] + $list['number'][11];
                    $infoList['number'][4] = $list['number'][12] + $list['number'][13];
                    $infoList['number'][5] = $list['number'][14] + $list['number'][15];
                    $infoList['number'][6] = $list['number'][16] + $list['number'][17];
                    $infoList['number'][7] = $list['number'][18] + $list['number'][19];
                    $infoList['number'][8] = $list['number'][20] + $list['number'][21];
                    $infoList['number'][9] = $list['number'][22] + $list['number'][23];
                    return response()->json(['code' => 200, 'msg' => '成功', 'data' => $infoList]);
                    break;
            }
        }
    }
    //周平均值
    public function avgByWeek($id)
    {
        $cmpId = $id;
        $orders = DB::table('visitorHistory')
            ->select(DB::raw("from_unixtime(visitTime,'%W') as week"), DB::raw("count(*) as count"))
            ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
            ->groupBy(DB::raw("from_unixtime(visitTime,'%W')"))
            ->get()->toArray();
        $data = [
            'week'=>['星期一','星期二','星期三','星期四','星期五','星期六','星期日'],
            'number'=>[0,0,0,0,0,0,0]
        ];
        if(empty($orders)){
            return response()->json(['code'=>200,'msg'=>'成功','data'=>$data]);
        }
        $user = DB::table('cmpInfo')
            ->where('id', '=', $cmpId)
            ->select(['id','userId'])
            ->first();
        $startTime = DB::table('userAdm')
            ->where('id', '=', $user->userId)
            ->select(['createdAt'])
            ->first();
        $endTime = time();
        $weeks = ceil(($endTime - $startTime->createdAt) / (24 * 3600 * 7));
        foreach($orders as $k=>$v){
            switch($v->week){
                case 'Monday':
                    $data['number'][0]=ceil($v->count/$weeks);
                    break;
                case 'Tuesday':
                    $data['number'][1]=ceil($v->count/$weeks);
                    break;
                case 'Wednesday':
                    $data['number'][2]=ceil($v->count/$weeks);
                    break;
                case 'Thursday':
                    $data['number'][3]=ceil($v->count/$weeks);
                    break;
                case 'Friday':
                    $data['number'][4]=ceil($v->count/$weeks);
                    break;
                case 'Saturday':
                    $data['number'][5]=ceil($v->count/$weeks);
                    break;
                case 'Sunday':
                    $data['number'][6]=ceil($v->count/$weeks);
                    break;
            }
        }
        ksort($data['number']);
        return response()->json(['code'=>200,'msg'=>'成功','data'=>$data]);
    }
    //天平均值
    public function avgByDay($id){
        $cmpId = $id;
        $orders = DB::table('visitorHistory')
            ->select(DB::raw("from_unixtime(visitTime,'%H') as hour"), DB::raw("count(*) as count"))
            ->where([['cmpId', '=', $cmpId],['isInvite','=','0']])
            ->groupBy(DB::raw("from_unixtime(visitTime,'%H')"))
            ->get();
        $user = DB::table('cmpInfo')
            ->where('id', '=', $cmpId)
            ->select(['id','userId'])
            ->first();
        $userInfo = DB::table('userAdm')
            ->where('id', '=', $user->userId)
            ->select(['createdAt'])
            ->first();
        $endTime = time();
        if(empty($userInfo)){
            $days =1 ;
        }else{
            $startTime = $userInfo->createdAt;
            $days = ceil(($endTime-$startTime)/(24*3600));
        }
       
        for($i=0;$i<24;$i++){
            if($i<10){
                $key = '0'.$i;
            }else{
                $key = (string)$i;
            }
            $list['day'][$i] =$key;
            $list['number'][$i] = 0;
        }
        if(!empty($orders)){
            foreach($orders as $k){
                if(in_array($k->hour,$list['day'])){
                    $key = (integer)$k->hour;
                    $list['number'][$key]=ceil($k->count/$days);
                }
            }
        }
        $infoList['number'][0] = 0;
        for($h = 0;$h<count($list['day']);$h++){
            if($h<6){
                $infoList['number'][0] += $list['number'][$h];
            }
        }
        $infoList['day'][0]='00:00-06:00';
        $infoList['day'][1]='06:00-08:00';
        $infoList['day'][2]='08:00-10:00';
        $infoList['day'][3]='10:00-12:00';
        $infoList['day'][4]='12:00-14:00';
        $infoList['day'][5]='14:00-16:00';
        $infoList['day'][6]='16:00-18:00';
        $infoList['day'][7]='18:00-20:00';
        $infoList['day'][8]='20:00-22:00';
        $infoList['day'][9]='22:00-24:00';
        $infoList['number'][1]=$list['number'][6]+$list['number'][7];
        $infoList['number'][2]=$list['number'][8]+$list['number'][9];
        $infoList['number'][3]=$list['number'][10]+$list['number'][11];
        $infoList['number'][4]=$list['number'][12]+$list['number'][13];
        $infoList['number'][5]=$list['number'][14]+$list['number'][15];
        $infoList['number'][6]=$list['number'][16]+$list['number'][17];
        $infoList['number'][7]=$list['number'][18]+$list['number'][19];
        $infoList['number'][8]=$list['number'][20]+$list['number'][21];
        $infoList['number'][9]=$list['number'][22]+$list['number'][23];
        return response()->json(['code'=>200,'msg'=>'成功','data'=>$infoList]);
    }
    //统计按钮点击模块次数
    public function clickCount(Request $request)
    {   
        $res = $request->all();
        $userId = Auth::id();
        $cmpInfo = DB::table('cmpInfo')->select('id')
        ->where('userId',$userId)->first();
        $cmpId = $cmpInfo->id;
        foreach($res['data'] as $key=>$val)
        {   
            $redisKey = $key.'_ClickCount_CmpId_'.$cmpId;
            !Redis::exists($redisKey) ? Redis::set($redisKey,$val) : Redis::Incrby($redisKey,$val);
        }
        return response()->json(['code'=>200,'msg'=>'成功','data'=>[]]);
    }
//    被访最多的人
    public function whoMost($id){
        $cmpId  = $id;
         $result = DB::table('visitorHistory')
            ->join('employeeInfo', 'visitorHistory.invitedId', '=', 'employeeInfo.id')
            ->select(['invitedId',DB::raw("count(*) as count"),'name'])
            ->where([['visitorHistory.cmpId', '=', $cmpId],['visitorHistory.isInvite','=','1']])
            ->groupBy('invitedId')
            ->limit(10)
            ->orderBy('count','desc')
            ->get();
        return response()->json(['code'=>200,'msg'=>'成功','data'=>$result]);
    }
}
